package com.xinongbest.mall.controller;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ThreadController {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(8);
        Producer producer = new Producer(queue);
        Thread thread = new Thread(producer);
        thread.start();
        Thread.sleep(500);

        Customer customer = new Customer(queue);
        while (customer.needMoreData()) {
            Object take = customer.queue.take();
            System.out.println(take + "被消费了");
            Thread.sleep(100);
        }
        System.out.println("消费者不需要更多数据了");
        producer.cancel = true;
        System.out.println(producer.cancel);
    }
}

class Producer implements Runnable {
    public volatile Boolean cancel = false;

    BlockingQueue<Integer> blockingQueue;

    public Producer(BlockingQueue<Integer> queue) {
        this.blockingQueue = queue;
    }

    @Override
    public void run() {
        int count = 0;
        try {
            while (count <= 10000 && !cancel) {
                if (count % 50 == 0) {
                    blockingQueue.put(count);
                    System.out.println(count + "是50的倍数，被放到容器队列中");
                }
                count++;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("生产者运营结束");
        }
    }
}

class Customer {
    BlockingQueue<Integer> queue;
    public Customer(BlockingQueue<Integer> queue) {
        this.queue = queue;
    }

    public boolean needMoreData() {
        if (Math.random() > 0.79) {
            return false;
        }
        return true;
    }
}
